package com.pingan.haofang.searchcloud.common.redis;

import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import java.util.List;

public final class RedisLuaScript {

    private RedisLuaScript() {
        throw new UnsupportedOperationException("Unsupported Operation");
    }

    /**
     * Lua脚本所在根路径
     */
    private static final String SCRIPT_ROOT = "/redis_lua_script/";

    private static class SingletonHolder {

        private static final RedisScript msgMergeScript;

        private static final RedisScript msgConsumeScript;

        static {
            DefaultRedisScript defaultMsgMergeRedisScript = new DefaultRedisScript<Long>();
            defaultMsgMergeRedisScript.setScriptSource(new ResourceScriptSource(
                    new ClassPathResource(SCRIPT_ROOT + "msg_merge_script.lua")));
            defaultMsgMergeRedisScript.setResultType(Long.class);
            msgMergeScript = defaultMsgMergeRedisScript;

            DefaultRedisScript defaultMsgConsumeRedisScript = new DefaultRedisScript<Long>();
            defaultMsgConsumeRedisScript.setScriptSource(new ResourceScriptSource(
                    new ClassPathResource(SCRIPT_ROOT + "msg_consume_script.lua")));
            defaultMsgConsumeRedisScript.setResultType(List.class);
            msgConsumeScript = defaultMsgConsumeRedisScript;
        }

        private static RedisScript<Long> msgMergeScriptInstance() {
            return msgMergeScript;
        }

        private static RedisScript<List> msgConsumeScriptInstance() {
            return msgConsumeScript;
        }
    }

    public static RedisScript<Long> msgMergeScript() {
        return SingletonHolder.msgMergeScriptInstance();
    }

    public static RedisScript<List> msgConsumeScript() {
        return SingletonHolder.msgConsumeScriptInstance();
    }
}
